package com.mmp.main.servlet.spinventory;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.mmp.common.bo.Message;
import com.mmp.common.bo.Message.MESSAGE_TYPE;
import com.mmp.common.servlet.BasicServlet;
import com.mmp.main.endpoints.SPInventoryNotificationsEndPoint;
import com.mmp.main.entity.SpInventoryContent;
import com.mmp.main.entity.SpInventoryTransaction;
import com.mmp.main.entity.User;
import com.mmp.main.util.WebUtil;

public class UpdateSPCategoryProcessServlet extends BasicServlet {

	@Autowired
	SPInventoryNotificationsEndPoint spCategoryNotifier;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {

		boolean inputOperType = WebUtil.getParamValue(request, "input", "1").equals("1") ? true : false;
		Integer quantity = WebUtil.getParamValueAsInteger(request, "quantity", 0);
		Float price = WebUtil.getParamValueAsFloat(request, "price", 0f);
		User currentUser = getSessionUser(request);
		Date now = new Date();

		SpInventoryContent spInventoryContent = dbQueryManager.findById(
				WebUtil.getParamValueAsInteger(request, "spCatId", 0), SpInventoryContent.class);

		if (!inputOperType && quantity > spInventoryContent.getAvailableQuantity()) {
			setMessage(request, new Message(
					"لا يمكن إتمام العملية .. الكمية المطلوب سحبها أكبر من الكمية المتاحة بالمستودع",
					MESSAGE_TYPE.ERROR));
			sendRedirect(request, response, "UpdateSPCategory?code=" + spInventoryContent.getCode());
			return;
		}

		spInventoryContent.setCode(WebUtil.getParamValue(request, "code", null));
		spInventoryContent.setName(WebUtil.getParamValue(request, "name", null));
		spInventoryContent.setThreshold(WebUtil.getParamValueAsInteger(request, "threshold", 0));

		if (quantity > 0) {
			int newQuantity = spInventoryContent.getAvailableQuantity() + ((inputOperType) ? quantity : -quantity);
			float newPrice = 0;
			if (newQuantity != 0) { // avoid division by zero
				newPrice = ((spInventoryContent.getAvgUnitPrice() * spInventoryContent.getAvailableQuantity()) + ((inputOperType) ? 1
						: -1)
						* (price * quantity))
						/ newQuantity;
			}
			spInventoryContent.setAvailableQuantity(newQuantity);
			spInventoryContent.setAvgUnitPrice(newPrice);
		}

		spInventoryContent.setLastModefiedBy(currentUser);
		spInventoryContent.setLastModefiedIn(now);

		spInventoryContent = dbQueryManager.mergeEntity(spInventoryContent);

		if (quantity > 0) {
			SpInventoryTransaction spInventoryTransaction = new SpInventoryTransaction();
			spInventoryTransaction.setSite(currentUser.getSite());
			spInventoryTransaction.setSpInventoryContent(spInventoryContent);
			spInventoryTransaction.setInput(inputOperType);
			spInventoryTransaction.setQuantity(quantity);
			spInventoryTransaction.setUnitPrice(price);
			spInventoryTransaction.setPerformedBy(currentUser);
			spInventoryTransaction.setPerformedIn(now);

			spInventoryTransaction = dbQueryManager.persistEntity(spInventoryTransaction);
		}

		spCategoryNotifier.broadcastNotificationUpdates(getSessionSiteId(request));

		setMessage(request, new Message("تم  تعديل  الصنف بنجاح", Message.MESSAGE_TYPE.SUCCESS));

		sendRedirect(request, response, "UpdateSPCategorySearch");
	}
}
